package com.cainli.gcmdemo;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;

public class ClientActivity extends Activity implements
		GCMIntentService.MessageListener {

	private static final String TAG = ClientActivity.class.getSimpleName();
	private TextView textView;
	private TextView registIdview;
	private TextView explainTextView;
	private static StringBuffer sb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		final String SENDER_ID = "772558295202";
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_layout);
		textView = (TextView) findViewById(R.id.text);
		explainTextView = (TextView) findViewById(R.id.path);
		explainTextView.setText(Constants.getExplainText());
		registIdview = (TextView) findViewById(R.id.registration_ids_value);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ClientActivity.this,
						ServerActivity.class);
				startActivity(intent);
			}
		});
		GCMIntentService.setListener(this);
		try {
			GCMRegistrar.checkDevice(this);
		} catch (Exception e) {
			Toast.makeText(this, "该设备没有google服务！", Toast.LENGTH_SHORT).show();
			finish();
		}
		// 创建数据文件
		if (!Utils.createDataFile(Constants.DATA_FILE_PATH)) {
			Toast.makeText(this, "不能创建数据文件！", Toast.LENGTH_SHORT).show();
			finish();
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append("ID").append("   ").append("server time").append("   ")
					.append("client time").append("   ").append("message")
					.append("   ").append("\n");
			Utils.saveMsg(sb.toString());
		}

		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			Utils.saveID(regId);
			registIdview.setText(regId);
			Log.v(TAG, "Already registered");
		}

		openFile();
	}

	private void openFile() {
		try {
			Utils.openFile();
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		}
	}

	@Override
	public void onRegistered(final String registrationId) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				registIdview.setText(registrationId);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public void onBackPressed() {
		if (ServerActivity.sendFinish) {
			GCMIntentService.setListener(null);
			closeFile();
			stopRecvService();
			ClientActivity.super.onBackPressed();
			super.onBackPressed();
			return;
		}
		final AlertDialog alertDialog = new AlertDialog.Builder(this)
				.setTitle("提示").setMessage("退出则停止写入文件！")
				.setIcon(R.drawable.ic_launcher)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						GCMIntentService.setListener(null);
						closeFile();
						stopRecvService();
						ClientActivity.super.onBackPressed();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).create();
		alertDialog.show();
	}

	private void closeFile() {
		try {
			Utils.close();
		} catch (IOException e) {
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void stopRecvService() {
		android.os.Process.killProcess(android.os.Process.myPid());   
		System.exit(0);   
	}

	@Override
	public void onRecvMessage(final String msg) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					// getSB().append(msg);
					// textView.setText(getSB().toString());
					textView.setText(msg);
				} catch (Exception e) {
				}
			}
		});
	}

	public StringBuffer getSB() {
		if (sb == null) {
			sb = new StringBuffer();
		}
		return sb;
	}
}
